<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10 paddingBottom20">
      <div class="mainor_form">
        <div class="mainor_te">
          <!-- type="primary" -->
          <el-button @click="jump()">差额流水</el-button>
        </div>
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="70px"
        >
          <el-form-item label="批发商" prop="dispatch_name">
            <el-input
              v-model.trim="form.dispatch_name"
              placeholder="批发商"
              clearable
              class="wid220"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button class="reset marginLeft10" type="primary" @click="reset"
              >重置</el-button
            >
            <el-button
              type="primary"
              @click="getArticleList"
              :loading="listLoading"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="main_num boxdq">
        <div class="main_num_l boxha">
          <p>
            应退金额：
            <em>{{ total.return }}</em>
          </p>
          <p>
            欠补金额：
            <em>{{ total.pay }}</em>
          </p>
        </div>
      </div>
      <div class="main_table" style="min-height: 570px">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          show-summary
          :summary-method="getSummaries"
        >
          <!-- :header-cell-class-name="this.$verticaline" -->
          <el-table-column label="批发商" prop="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{
                scope.row.dispatch_name
                  ? scope.row.dispatch_name.company_name
                  : ""
              }}
            </template>
          </el-table-column>

          <el-table-column
            label="在线支付差额"
            prop="balance"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="管理操作" fixed="right" width="200">
            <template slot-scope="scope">
              <el-link type="warning" @click="handle_pay_bulk_balance(scope)"
                >结差额</el-link
              >
              <el-link type="success" @click="jump(scope)">记录</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <el-pagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <!-- 二维码 -->
    <el-dialog
      title="二维码"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
      :visible.sync="addedFormVisible"
      class="main_dialog dialog500"
    >
      <div class="qrcode_box">
        <p>
          金额：<span>{{ qrcode_box_info.order_money }}元</span>
        </p>
        <p>订单号：{{ qrcode_box_info.order_sn }}</p>
      </div>
      <div
        id="qrcode"
        style="margin: auto; width: 200px"
        class="marginTop10 marginBottom20"
      ></div>
    </el-dialog>
  </div>
</template>

<script>
import {
  get_bulk_balance_index,
  pay_bulk_balance,
  close_bulk_balance,
  query_bulk_balance
} from "@/api/bulk/bulkBalance";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";
import dateOption from "@/options/dateOption";
import QRCode from "qrcodejs2";

export default {
  data() {
    return {
      pickerOptions: dateOption,
      // 搜索
      form: {
        dispatch_name: "" //批发商姓名
      },
      addedFormVisible: false,
      // 更多
      moredata: false,
      // 列表数据
      list: [],
      listLoading: false,
      // 分页
      current: {
        page: 1,
        per_page: 20
      },
      limit: 20,
      totalCount: 1,
      // 合计数据
      total: {
        balance: 0,
        pay: 0,
        return: 0
      },
      qrCodeId: "",
      qrcode_box_info: {},
      close_form: {
        company_id: "",
        id: ""
      },
      query_timer: ""
    };
  },
  methods: {
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.get_bulk_balance_index();
    },
    changePage(page) {
      this.current.page = page;
      this.get_bulk_balance_index();
    },

    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.get_bulk_balance_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();

      this.get_bulk_balance_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    get_bulk_balance_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.form,
        this.current
      );
      get_bulk_balance_index(data).then(res => {
        if (res.errcode == 0) {
          this.totalCount = res.data.list.total;
          let count = 0;
          res.data.list.data.map(e => {
            count += parseFloat(e.balance);
          });
          this.total.balance = this.$toFixed(count);
          this.list = res.data.list.data;
          this.total.pay = this.$toFixed(res.data.pay);
          this.total.return = this.$toFixed(res.data.return);
          this.listLoading = false;
          console.log(this.list);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 差额流水跳转
    jump(scope) {
      var dispatch_name = "";
      if (scope) {
        dispatch_name = scope.row.dispatch_name.company_name;
        this.$router.push({
          name: "bulk_balance_flowing",
          query: {
            dispatch_name: dispatch_name
          }
        });
      } else {
        this.$router.push({
          name: "bulk_balance_flowing"
        });
      }
    },

    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        switch (index) {
          case 0:
            sums[index] = "合计";
            break;
          case 1:
            sums[index] = this.$toFixed(this.total.balance);
            break;
        }
      });
      return sums;
    },
    /* 结差额 */
    handle_pay_bulk_balance(scope) {
      if (parseFloat(scope.row.balance) >= 0) {
        this.bulk_balance_plus();
      } else {
        this.bulk_balance_min(scope);
      }
    },

    bulk_balance_plus() {
      this.$confirm("差额为正数时，需批发商发起结差额！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {

        })
        .catch(() => {
          
        });
    },

    bulk_balance_min(scope) {
      let company_id = scope.row.company_id;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { company_id: company_id }
      );
      pay_bulk_balance(data).then(res => {
        if (res.errcode == 0) {
          this.addedFormVisible = true;
          this.close_form.id = res.data.order.id;
          this.qrcode_box_info = res.data.order;
          this.close_form.company_id = res.data.order.company_id;
          this.$nextTick(() => {
            let qrcode = new QRCode("qrcode", {
              width: 200,
              height: 200,
              text: JSON.parse(res.data.res).billQRCode
            });
          });
          this.query_timer = setInterval(() => {
            this.query_bulk()
              .then(res => {
                this.$message.success("支付成功");
                this.close();
                this.addedFormVisible = false;
              })
              .catch(err => {});
          }, 1500);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    close() {
      clearInterval(this.query_timer);
      document.getElementById("qrcode").innerHTML = "";
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.close_form
      );
      close_bulk_balance(data).then(res => {
        if (res.errcode == 0) {
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    query_bulk() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.close_form
      );
      return new Promise((resolve, reject) => {
        query_bulk_balance(data).then(res => {
          if (res.errcode == 0) {
            resolve();
          } else {
            reject(res);
          }
        });
      });
    }
  },
  created() {
    // 列表
    this.get_bulk_balance_index();
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.mainor_form form {
  width: calc(100% - 280px);
}
.qrcode_box {
  font-size: 16px;
  margin: auto;
  width: 200px;
  p {
    line-height: 1.5;
    &:first-child {
      span {
        color: red;
        font-size: 18px;
        font-weight: 700;
      }
    }
  }
}
</style>
